import json,datetime,random,requests
from alipay import AliPay
from flask_restful import Resource
from flask import redirect,request

# 支付宝支付：用的三方库AliPay
def out_trade_no():
    '''
    :return: 生成订单号
    '''
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    randomNum = random.randint(0,100)
    if randomNum <= 10:
        randomNum = str(0)+str(randomNum)
    uniqueNum = str(nowTime)+str(randomNum)
    return uniqueNum


my_alipay = AliPay(
    appid=2018010201507862,
    app_notify_url="https://api.lo.o3.vc/pay",
    app_private_key_path="./lolita//api/RSA/privatekey2048.txt",
    alipay_public_key_path="./lolita//api/RSA/publickey2048.txt",  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
    sign_type="RSA2",  # RSA 或者 RSA2
    debug=False,  # 默认False
)

def create_run():
    order_string = my_alipay.api_alipay_trade_wap_pay(
        out_trade_no=out_trade_no(),
        total_amount=0.01,
        subject='友情赞助咩哈哈哈哈',
        return_url="http://h5.lo.o3.vc",
        notify_url="https://api.lo.o3.vc/pay"  # 可选, 不填则使用默认notify url
    )
    return order_string

def refund(out_trade_no,refund_amount ):
    """
    :param out_trade_no:
    :param refund_amount:
    :return: 退款
    """
    result = my_alipay.api_alipay_trade_refund(
        out_trade_no=out_trade_no,
        refund_amount=refund_amount,
    )
    return result


class Pay(Resource):
    def get(self):
        order_string = create_run()
        url = 'https://openapi.alipay.com/gateway.do'
        return redirect(url + '?' + order_string)

    def post(self):
        if request.method == 'POST':
            data = request.form.to_dict()
            signature = data.pop("sign")
            success = my_alipay.verify(data, signature)
            if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                print("trade succeed")
                return "success"
        return 'fail'


class Refund(Resource):
    def get(self):
        out_trade_no = request.args.get('out_trade_no')
        refund_amount = request.args.get('refund_amount')
        order_string = refund(out_trade_no,refund_amount)
        url = 'https://openapi.alipay.com/gateway.do '
        return redirect(url+order_string)











